import { defineStore } from 'pinia'
import { listEntries, getEntry, type Entry } from '@/api/entries'

export type Visibility = 'private' | 'friends' | 'public'

export type Article = Entry & {
  visibility: Visibility
  tags: string[]
}

interface State {
  list: Article[]
  total: number
  loading: boolean
  loaded: boolean
  error: string | null
}

function normalizeVisibility(v: any): Visibility {
  if (v === 'private' || v === 'friends' || v === 'public') return v
  if (v === 0 || v === '0') return 'private'
  if (v === 1 || v === '1') return 'friends'
  if (v === 2 || v === '2') return 'public'
  return 'private'
}

function normalizeTags(e: any): string[] {
  const tags: string[] = []
  const source = e?.tags ?? e?.entry_tags ?? e?.tags_rel ?? e?.tagNames ?? []
  if (Array.isArray(source)) {
    for (const t of source) {
      if (typeof t === 'string') tags.push(t)
      else if (t && typeof t === 'object') {
        if (typeof (t as any).name === 'string') tags.push((t as any).name)
        else if (t.tag && typeof t.tag.name === 'string') tags.push(t.tag.name)
      }
    }
  } else if (typeof source === 'string') {
    // 逗号分隔字符串
    source.split(',').map(s => s.trim()).filter(Boolean).forEach(s => tags.push(s))
  }
  // 去重
  return Array.from(new Set(tags))
}

function normalizeEntry(e: any): Article {
  const createdAt = e?.created_at || e?.createdAt || new Date().toISOString()
  return {
    ...(e as Entry),
    visibility: normalizeVisibility(e?.visibility),
    tags: normalizeTags(e),
    created_at: createdAt,
  }
}

export const useEntriesStore = defineStore('entries', {
  state: (): State => ({
    list: [],
    total: 0,
    loading: false,
    loaded: false,
    error: null,
  }),
  persist: {
    key: 'mirrorforest-entries-store',
    storage: window.localStorage,
    paths: ['list', 'total', 'loaded'],
  } as any,
  getters: {
    byId: (state) => (id: number | string) => state.list.find(e => e.id === Number(id)),
  },
  actions: {
    async fetch(params: { userId: number, title: string }) {
      this.loading = true
      this.error = null
      try {
        console.log(2);
        const res: any = await listEntries(params)
        console.log('Raw response:', res);
        const ok = res && (res.success === true || res.code === 0 || res.code === 200)
        if (!ok) throw new Error(res?.message || '加载文章失败')
        const data = res?.data ?? {}
        console.log('Fetched entries data:', data);
        const rawList = Array.isArray(data?.list) ? data.list : (Array.isArray(data) ? data : (Array.isArray(res) ? res : []))
        const total = typeof data?.total === 'number' ? data.total : rawList.length
        const normalized = (rawList as any[]).map(normalizeEntry)
        this.list = normalized
        this.total = total
        this.loaded = true
        return { list: normalized, total }
      } catch (e: any) {
        this.error = e?.message || '加载文章失败'
        throw e
      } finally {
        this.loading = false
      }
    },
    async fetchById(id: number | string) {
      this.loading = true
      this.error = null
      try {
        const res: any = await getEntry(id)
        const ok = res && (res.success === true || res.code === 0 || res.code === 200)
        if (!ok) throw new Error(res?.message || '加载文章详情失败')
        const raw = res?.data ?? res
        const item = normalizeEntry(raw)
        const idx = this.list.findIndex(e => e.id === Number(id))
        if (idx >= 0) this.list.splice(idx, 1, item)
        else this.list.unshift(item)
        return item
      } catch (e: any) {
        this.error = e?.message || '加载文章详情失败'
        throw e
      } finally {
        this.loading = false
      }
    },
  }
})
